﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using GMAC.ReportingSystem.Business.Entities;
using Components = GMAC.ReportingSystem.Business.Components;
using Entities = GMAC.ReportingSystem.Business.Entities;

namespace GMAC.ReportingSystem.Paginas
{
    public partial class ManagementRoles : Page
    {
        #region Page Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated || Session["User"] == null)
            {
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                return;
            }
            if (IsPostBack) return;
            Initialize();
            ValidateSecurity();
        }

        #endregion

        #region Button Events

        protected void btnNew_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var bcRole = new Components.RoleComponent();
                var beRole = ReadRole();
                beRole.RoleID = bcRole.Create(beRole);
                var audit = new FrameworkManapro.Audit.Audit<Role>
                {
                    EntityKey = beRole.RoleID.ToString(),
                    EventDate = DateTime.Now,
                    EventType = FrameworkManapro.Audit.AuditEvent.Insert,
                    NewObject = beRole,
                    UserId = ((User)Session["User"]).UserID
                };
                var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Role>(audit);
                auditDAC.InsertAudit();
                wucMessage.ShowMessage(UserControls.MessageType.Success, "The role was successfully saved.", null);
                popupExtenderMessage.Show();
                Search();
                ClearFields();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "New role", "btnNew_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The role could not be saved", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnSave_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            btnNew.Visible = true;
            var bcRole = new Components.RoleComponent();
            try
            {
                var beRole = ReadRole();
                if (hfRolId.Value.Trim() != string.Empty)
                {
                    beRole.RoleID = int.Parse(hfRolId.Value);
                    var oldRole = bcRole.GetDetails(beRole.RoleID);
                    bcRole.Edit(beRole);
                    var audit = new FrameworkManapro.Audit.Audit<Role>
                    {
                        EntityKey = beRole.RoleID.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Update,
                        OldObject = oldRole,
                        NewObject = beRole,
                        UserId = ((User)Session["User"]).UserID
                    };
                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Role>(audit);
                    auditDAC.InsertAudit();
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The role was successfully saved.", null);
                    popupExtenderMessage.Show();
                    Search();
                    ClearFields();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Save role", "btnSave_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The role couldn't be saved.", null);
                popupExtenderMessage.Show();

            }
        }
        protected void btnCancel_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            btnNew.Visible = true;
            ClearFields();
        }
        protected void btnModify_Click(object sender, ImageClickEventArgs e)
        {
            if (grvRoles.SelectedDataKey != null)
            {
                try
                {
                    var roleId = (int)grvRoles.SelectedDataKey.Value;
                    var beRole = new Components.RoleComponent();
                    var role = beRole.GetDetails(roleId);
                    hfRolId.Value = roleId.ToString();
                    txtName.Text = role.Name;
                    txtDescription.Text = role.Description;
                    Search();
                    UpdateNavigation(role.Security.Menus);
                    UpdatePermits(role.Security.Entities);
                    //UpdateReports(role.Security.Reports);
                    btnSave.Visible = true;
                    btnNew.Visible = false;
                }
                catch (Exception ex)
                {
                    FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Modify role", "btnModify_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                    wucMessage.ShowMessage(UserControls.MessageType.Error, "An error occurred changing the role.", ex.ToString());
                    popupExtenderMessage.Show();
                }
            }
            else
            {
                wucMessage.ShowMessage(UserControls.MessageType.Information, "A role must be selected.", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnDelete_Click(object sender, ImageClickEventArgs e)
        {
            if (grvRoles.SelectedDataKey != null)
            {
                popupExtenderConfirm.Show();
            }
            else
            {
                wucMessage.ShowMessage(UserControls.MessageType.Information, "A role must be selected.", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnConfirm_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var bcRole = new Components.RoleComponent();
                if (grvRoles.SelectedDataKey != null)
                {
                    var roleId = (int)grvRoles.SelectedDataKey.Value;
                    var beRole = new Role { RoleID = roleId };
                    var oldRole = bcRole.GetDetails(beRole.RoleID);
                    bcRole.Delete(beRole);
                    var audit = new FrameworkManapro.Audit.Audit<Role>
                    {
                        EntityKey = beRole.RoleID.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Delete,
                        OldObject = oldRole,
                        UserId = ((User)Session["User"]).UserID
                    };
                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Role>(audit);
                    auditDAC.InsertAudit();
                    Search();
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The role was successfully deleted.", null);
                    popupExtenderMessage.Show();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Delete role", "btnConfirm_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The role couldn't be deleted.", ex.ToString());
                popupExtenderMessage.Show();

            }
        }
        protected void imgBuscarReg_Click(object sender, ImageClickEventArgs e)
        {
            Search();
        }
        protected void btnPermits_Click(object sender, ImageClickEventArgs e)
        {
            popupExtenderNavigation.Show();
        }
        protected void btnAceptNavigation_Click(object sender, ImageClickEventArgs e)
        {
            popupExtenderPermits.Show();
        }

        #endregion

        #region Other Events

        protected void grvRoles_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["OnClick"] = ClientScript.GetPostBackEventReference(grvRoles, "Select$" + e.Row.RowIndex);
                if (bool.Parse((e.Row.FindControl("hfStatus") as HiddenField).Value) == true)
                {
                    e.Row.Cells[2].Text = "Active";
                }
                else
                {
                    e.Row.Cells[2].Text = "Inactive";
                }
            }
        }
        protected void grvPermits_RowDataBound(object sender, GridViewRowEventArgs e)
        {

        }

        #endregion

        #region Private Methods

        private void Initialize()
        {
            Search();
            grvPermits.Columns[0].Visible = false;
            grvPermits.Columns[1].Visible = false;
            optOptions.SelectedValue = "True";
            btnSave.Visible = false;
            btnNew.Visible = true;
            wucMessageConfirm.ShowMessage(UserControls.MessageType.Information, "Are you sure you want to delete the selected role?", null);
        }
        private void ClearFields()
        {
            txtName.Text = string.Empty;
            txtDescription.Text = string.Empty;
            //var bcReport = new Components.ReportComponent();
            //var ReportProjectName = System.Configuration.ConfigurationManager.AppSettings["nameAplication"];
            var beSecurity = new Components.SecurityComponent();
            CreateMenu();
            grvPermits.DataSource = beSecurity.GetEntities();
            grvPermits.DataBind();
            //grvReports.DataSource = bcReport.GetList(ReportProjectName);
            //grvReports.DataBind();
        }
        private void Search()
        {
            try
            {
                var bcRole = new Components.RoleComponent();
                var beSecurity = new Components.SecurityComponent();
                //var bcReport = new Components.ReportComponent();
                var beRole = bcRole.GetList();
                var RoleName = txtNameSearch.Text;
                //var ReportProjectName = System.Configuration.ConfigurationManager.AppSettings["nameAplication"];

                CreateMenu();
                grvRoles.DataSource = bcRole.Search(RoleName);
                grvRoles.DataBind();
                grvPermits.DataSource = beSecurity.GetEntities();
                grvPermits.DataBind();
                //grvReports.DataSource = bcReport.GetList(ReportProjectName);
                //grvReports.DataBind();


            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Search role", "void Search", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred during the search. ", ex.ToString());
                popupExtenderMessage.Show();
            }
        }
        private void CreateMenu()
        {
            var beSecurity = new Components.SecurityComponent();
            var beMenu = beSecurity.GetMenus();
            grvNavigation.DataSource = beMenu;
            grvNavigation.DataBind();
        }
        private void UpdateNavigation(MenuCollection beMenu)
        {
            Label lblMenu;
            Label lblName;
            GridView grvSubMenu;
            CheckBox chkActive;
            foreach (var roleMenu in beMenu)
            {
                foreach (GridViewRow row in grvNavigation.Rows)
                {
                    lblMenu = row.FindControl("lblMenu") as Label;
                    if (lblMenu != null)
                        if (roleMenu.Name == lblMenu.Text)
                        {
                            grvSubMenu = row.FindControl("grvSubMenu") as GridView;
                            foreach (var roleSubMenu in roleMenu.SubMenus)
                            {
                                if (grvSubMenu != null)
                                    foreach (GridViewRow rowSubMenu in grvSubMenu.Rows)
                                    {
                                        lblName = rowSubMenu.FindControl("lblName") as Label;
                                        if (lblName != null)
                                            if (roleSubMenu.Name == lblName.Text)
                                            {
                                                chkActive = rowSubMenu.FindControl("chkActive") as CheckBox;
                                                if (chkActive != null) chkActive.Checked = true;
                                                else if (chkActive != null) chkActive.Checked = false;
                                                break;
                                            }
                                    }
                            }

                        }
                }
            }
        }
        private void UpdatePermits(EntitiesSecurityCollection beEntities)
        {
            Label lblEntity;
            CheckBox chkRead;
            CheckBox chkWrite;
            CheckBox chkInsert;
            CheckBox chkDelete;
            //CheckBox chkAnnuled;
            //CheckBox chkapprove_flat_amount;
            foreach (var entity in beEntities)
            {
                foreach (GridViewRow rowEntity in grvPermits.Rows)
                {
                    lblEntity = rowEntity.FindControl("lblEntity") as Label;
                    if (lblEntity != null)
                        if (entity.DisplayName == lblEntity.Text)
                        {

                            chkRead = rowEntity.FindControl("chkRead") as CheckBox;
                            if (entity.CanRead)
                            {
                                if (chkRead != null) chkRead.Checked = true;
                            }
                            else if (chkRead != null) chkRead.Checked = false;
                            chkWrite = rowEntity.FindControl("chkWrite") as CheckBox;
                            if (entity.CanWrite)
                            {
                                if (chkWrite != null) chkWrite.Checked = true;
                            }
                            else if (chkWrite != null) chkWrite.Checked = false;
                            chkInsert = rowEntity.FindControl("chkInsert") as CheckBox;
                            if (entity.CanInsert)
                            {
                                if (chkInsert != null) chkInsert.Checked = true;
                            }
                            else if (chkInsert != null) chkInsert.Checked = false;
                            chkDelete = rowEntity.FindControl("chkDelete") as CheckBox;
                            if (entity.CanDelete)
                            {
                                if (chkDelete != null) chkDelete.Checked = true;
                            }
                            else if (chkDelete != null) chkDelete.Checked = false;
                            //chkAnnuled = rowEntity.FindControl("chkAnnuled") as CheckBox;
                            //if (entity.CanAnnuled)
                            //{
                            //    if (chkAnnuled != null) chkAnnuled.Checked = true;
                            //}
                            //else if (chkAnnuled != null) chkAnnuled.Checked = false;
                            //chkapprove_flat_amount = rowEntity.FindControl("chkapprove_flat_amount") as CheckBox;
                            //if (entity.CanApproveFlatAmount)
                            //{
                            //    if (chkapprove_flat_amount != null) chkapprove_flat_amount.Checked = true;
                            //}
                            //else if (chkapprove_flat_amount != null) chkapprove_flat_amount.Checked = false;
                            break;
                        }

                }
            }
        }
        //private void UpdateReports(ReportCollection beReport)
        //{
        //    Label lblReportName;
        //    CheckBox chkReportActive = null;
        //    foreach (var report in beReport)
        //    {
        //        foreach (GridViewRow rowReport in grvReports.Rows)
        //        {
        //            lblReportName = rowReport.FindControl("lblReportName") as Label;
        //            if (lblReportName != null)
        //                if (report.Name == lblReportName.Text)
        //                {
        //                    if (report.Active)
        //                        chkReportActive = rowReport.FindControl("chkReportActive") as CheckBox;
        //                    if (chkReportActive != null) chkReportActive.Checked = true;
        //                    else if (chkReportActive != null) chkReportActive.Checked = false;
        //                    break;
        //                }
        //        }
        //    }
        //}
        //private ReportCollection ReadReport()
        //{
        //    HiddenField hidReportID;
        //    Label lblReportName;
        //    CheckBox chkReportActive;
        //    var beReports = new ReportCollection();
        //    Report beReport;
        //    foreach (GridViewRow rowReport in grvReports.Rows)
        //    {
        //        if (rowReport.RowType == DataControlRowType.DataRow)
        //        {
        //            hidReportID = rowReport.FindControl("hidReportID") as HiddenField;
        //            lblReportName = rowReport.FindControl("lblReportName") as Label;
        //            beReport = new Report
        //            {
        //                ReportID = new Guid(hidReportID.Value),
        //                Name = lblReportName.Text
        //            };
        //            chkReportActive = rowReport.FindControl("chkReportActive") as CheckBox;
        //            if (chkReportActive != null && chkReportActive.Checked)
        //                beReport.Active = true;
        //            beReports.Add(beReport);
        //        }
        //    }
        //    return beReports;
        //}
        private MenuCollection ReadMenu()
        {
            Label lblMenu;
            Label lblName;
            GridView grvSubMenu;
            CheckBox chkActive;
            var beMenus = new MenuCollection();
            Entities.Menu beMenu;
            Entities.Menu beSubMenu;
            var beSecurity = new Components.SecurityComponent();
            Entities.MenuCollection menus = beSecurity.GetMenus();
            foreach (GridViewRow rowMenu in grvNavigation.Rows)
            {
                lblMenu = rowMenu.FindControl("lblMenu") as Label;
                grvSubMenu = rowMenu.FindControl("grvSubMenu") as GridView;
                foreach (var menu in menus)
                {
                    if (lblMenu != null)
                        if (menu.Name == lblMenu.Text)
                        {
                            beMenu = new Entities.Menu
                            {
                                MenuId = menu.MenuId,
                                Name = menu.Name,
                                Description = menu.Description,
                                URL = menu.URL,
                                Action = menu.Action,
                                SubMenus = new MenuCollection()
                            };
                            if (grvSubMenu != null)
                            {
                                foreach (GridViewRow rowSubMenu in grvSubMenu.Rows)
                                {
                                    lblName = rowSubMenu.FindControl("lblName") as Label;
                                    chkActive = rowSubMenu.FindControl("chkActive") as CheckBox;
                                    if (chkActive != null)
                                        if (chkActive.Checked)
                                        {
                                            foreach (var subMenu in menu.SubMenus)
                                            {
                                                if (lblName != null)
                                                    if (subMenu.Name == lblName.Text)
                                                    {
                                                        beSubMenu = new Entities.Menu
                                                        {
                                                            MenuId = subMenu.MenuId,
                                                            Name = subMenu.Name,
                                                            Description = subMenu.Description,
                                                            URL = subMenu.URL,
                                                            Action = subMenu.Action
                                                        };
                                                        beMenu.SubMenus.Add(beSubMenu);
                                                        break;
                                                    }
                                            }
                                        }
                                }
                            }
                            beMenus.Add(beMenu);
                            break;
                        }
                }

            }
            return beMenus;
        }
        private EntitiesSecurityCollection ReadEntities()
        {
            Label lblEntity;
            CheckBox chkRead;
            CheckBox chkWrite;
            CheckBox chkInsert;
            CheckBox chkDelete;
            //CheckBox chkAnnuled;
            //CheckBox chkapprove_flat_amount;
            var beEntities = new EntitiesSecurityCollection();
            EntitySecurity beEntity;
            var beSecurity = new Components.SecurityComponent();
            var entities = beSecurity.GetEntities();

            foreach (GridViewRow rowEntity in grvPermits.Rows)
            {
                foreach (var entity in entities)
                {
                    lblEntity = rowEntity.FindControl("lblEntity") as Label;
                    if (lblEntity != null)
                        if (entity.DisplayName == lblEntity.Text)
                        {
                            beEntity = new EntitySecurity
                            {
                                EntityID = entity.EntityID,
                                EntityName = entity.EntityName,
                                DisplayName = entity.DisplayName,

                            };
                            chkRead = rowEntity.FindControl("chkRead") as CheckBox;
                            if (chkRead != null && chkRead.Checked)
                                beEntity.CanRead = true;
                            chkWrite = rowEntity.FindControl("chkWrite") as CheckBox;
                            if (chkWrite != null && chkWrite.Checked)
                                beEntity.CanWrite = true;
                            chkInsert = rowEntity.FindControl("chkInsert") as CheckBox;
                            if (chkInsert != null && chkInsert.Checked)
                                beEntity.CanInsert = true;
                            chkDelete = rowEntity.FindControl("chkDelete") as CheckBox;
                            if (chkDelete != null && chkDelete.Checked)
                                beEntity.CanDelete = true;
                            //chkAnnuled = rowEntity.FindControl("chkAnnuled") as CheckBox;
                            //if (chkAnnuled != null && chkAnnuled.Checked)
                            //    beEntity.CanAnnuled = true;
                            //chkapprove_flat_amount = rowEntity.FindControl("chkapprove_flat_amount") as CheckBox;
                            //if (chkapprove_flat_amount != null && chkapprove_flat_amount.Checked)
                            //    beEntity.CanApproveFlatAmount = true;
                            beEntities.Add(beEntity);
                            break;
                        }

                }
            }
            return beEntities;
        }
        private Role ReadRole()
        {
            var beRole = new Role
            {
                Name = txtName.Text,
                Description = txtDescription.Text,
                Status = bool.Parse(optOptions.SelectedValue),
                Security = new Security(),
            };
    
            
            beRole.Security.Menus = ReadMenu();
            beRole.Security.Entities = ReadEntities();
            beRole.Security.Reports = new ReportCollection(); 
            return beRole;
        }
        private void ValidateSecurity()
        {
            var beEntities = ((User)Session["User"]).Role.Security.GetEntitySecurity("Role");
            if (beEntities == null) return;
            if (!beEntities.CanRead)
            {
                grvRoles.Visible = false;
                btnModify.Visible = false;
                btnDelete.Visible = false;
                pnlSearch.Visible = false;
            }
            if (!beEntities.CanWrite)
            {
                btnSave.Visible = false;
            }
            if (!beEntities.CanInsert)
            {
                btnNew.Visible = false;
                btnCancel.Visible = false;
                pnlEdit.Visible = false;
            }
            if (!beEntities.CanDelete)
            {
                btnDelete.Visible = false;
            }
        }

        #endregion
    }
}
